import { Modal, Button, Form, Select, DatePicker, Cascader } from 'antd';
import type { CascaderProps } from 'antd';
import type { RangePickerProps } from 'antd/es/date-picker';
import dayjs from 'dayjs';
import { useEffect, useState } from 'react';
import { skillTypeList, getCoreRegion } from '@/api/user';
import moment from 'moment';
// #474747
interface Option {
    value?: string | number | null;
    label: React.ReactNode;
    children?: Option[];
    isLeaf?: boolean;
}
// const FilterModal = (props: { open: boolean; onCancel: any }) => {
const FilterModal = (props: any) => {
    const { open, onCancel, onConfirm } = props;
    const [filterForm] = Form.useForm();
    const { RangePicker } = DatePicker;
    const onFinish = (values: any) => {
        console.log(values, 9);
        //
    };
    const [skillList, setSkillList] = useState<
        {
            eqSkillTypeDesc: string;
            eqSkillTypeId: string;
            eqSkillTypeName: string;
            value: string;
            label: string;
        }[]
    >([]);
    const [currentRegion, setCurrentRegion] = useState<Option[]>([]);
    const [selectRegionList, setSelectRegionList] = useState<string[]>([]);
    useEffect(() => {
        getSkill();
        fetchFirstLevelOptions();
        // getRegion('');
    }, []);
    const closeModal = () => {
        filterForm.resetFields();
        onConfirm({});
    };
    const closeIcon = () => {
        onCancel();
    };
    const filterOver = () => {
        const obj = filterForm.getFieldsValue();
        const { creatioTime } = obj;
        const startTime =
            creatioTime && creatioTime.length > 0
                ? dayjs(creatioTime[0]).startOf('date').format('YYYY-MM-DDTHH:mm:ss')
                : '';
        const endTime =
            creatioTime && creatioTime.length > 0
                ? dayjs(creatioTime[1]).endOf('date').format('YYYY-MM-DDTHH:mm:ss')
                : '';
        obj.sTime = startTime;
        obj.eTime = endTime;
        const currentProvinceCode = selectRegionList.length > 0 ? selectRegionList[0] : '';
        const currentCityCode = selectRegionList.length > 1 ? selectRegionList[1] : '';
        const currentDistrictCode = selectRegionList.length > 2 ? selectRegionList[2] : '';
        obj.currentProvinceCode = currentProvinceCode;
        obj.currentCityCode = currentCityCode;
        obj.currentDistrictCode = currentDistrictCode;
        const obj1 = JSON.parse(JSON.stringify(obj));

        onConfirm(obj1);
    };
    const getSkill = () => {
        const params = {};
        skillTypeList(params).then((res: any) => {
            console.log(res, 990);
            res.length > 0 &&
                res.map((item: any) => {
                    item.value = item.eqSkillTypeId;
                    item.label = item.eqSkillTypeName;
                });
            setSkillList(res);
        });
    };
    const formItems = [
        {
            type: 'select',
            label: 'Age range',
            key: 'ageRange',
            options: [
                { value: '0-18', label: '18及以下' },
                { value: '18-25', label: '18-25' },
                { value: '26-32', label: '26-32' },
                { value: '33-41', label: '33-41' },
                { value: '42-55', label: '42-55' },
                { value: '55-200', label: '55+' },
            ],
            placeholder: 'Select age range',
        },
        {
            type: 'select',
            label: 'Gender',
            key: 'userGender',
            options: [
                { value: '0', label: 'Other' },
                { value: '1', label: 'Male' },
                { value: '2', label: 'Female' },
            ],
            placeholder: 'Select gender',
        },
        {
            type: 'select',
            label: 'Occupation',
            key: 'professionId',
            options: skillList,
            placeholder: 'Select occupation',
        },
        {
            type: 'select',
            label: 'MBTI personality',
            key: 'personality',
            options: [
                { value: 'INTP', label: 'INTP' },
                { value: 'INTJ', label: 'INTJ' },
                { value: 'ENTJ', label: 'ENTJ' },
                { value: 'ENTP', label: 'ENTP' },
                { value: 'ENFP', label: 'ENFP' },
                { value: 'INFP', label: 'INFP' },
                { value: 'ENFJ', label: 'ENFJ' },
                { value: 'INFJ', label: 'INFJ' },
                { value: 'ISTJ', label: 'ISTJ' },
                { value: 'ISFJ', label: 'ISFJ' },
                { value: 'ESTJ', label: 'ESTJ' },
                { value: 'ESFJ', label: 'ESFJ' },
                { value: 'ISTP', label: 'ISTP' },
                { value: 'ISFP', label: 'ISFP' },
                { value: 'ESTP', label: 'ESTP' },
                { value: 'ESFP', label: 'ESFP' },
            ],
            placeholder: 'Select MBTI Personality',
        },
        {
            type: 'select',
            label: 'Status',
            key: 'disabled',
            options: [
                { value: false, label: 'Active' },
                { value: true, label: 'Suspended' },
            ],
            placeholder: 'Select status',
        },
        {
            type: 'date-picker',
            label: 'Creation time',
            key: 'creatioTime',
            options: [],
            placeholder: 'Select city',
        },
        // {
        //     type: 'select',
        //     label: 'Place of residence',
        //     key: 'residence',
        //     options: [
        //         { value: 'level1', label: '18-25' },
        //         { value: 'level2', label: '26-32' },
        //     ],
        // },
    ];
    const disabledDate: RangePickerProps['disabledDate'] = current => {
        return current && current > dayjs().endOf('day');
    };
    // 从这里开始  级联选择器
    const dateOnChange = date => {
        console.log(date);
    };
    const [cascaderOptions, setOptions] = useState<Option[]>([]);
    const fetchFirstLevelOptions = async () => {
        try {
            const params = {
                parentCode: '',
            };
            const response: any = await getCoreRegion(params);
            const list = response.map((item: any) => ({
                value: item.code,
                label: item.value,
                isLeaf: !item.hasSubValue, //  设为 `false` 时会强制标记为父节点，即使当前节点没有 children，也会显示展开图标 ，设为true，就是不展示有子节点的图标
            }));
            setOptions(list);
        } catch (error) {
            console.error('Failed to fetch first level options', error);
        }
    };

    const loadData = async (selectedOptions: Option[]) => {
        const targetOption = selectedOptions[selectedOptions.length - 1];
        try {
            const params = {
                parentCode: targetOption.value || '',
            };
            const response: any = await getCoreRegion(params);
            const list = response.map((item: any) => ({
                value: item.code,
                label: item.value,
                isLeaf: !item.hasSubValue,
            }));
            setOptions(list);
            targetOption.children = list;
            setOptions([...cascaderOptions]);
        } catch (error) {
            console.error('Failed to fetch next level options', error);
            setOptions([...cascaderOptions]);
        }
    };
    const onChange = (value, selectedOptions) => {
        console.log(value, selectedOptions);
        setSelectRegionList(value);
    };
    //   从这里结束 级联选择器
    return (
        <Modal
            width={480}
            maskClosable={false}
            centered
            open={open}
            closeIcon={<img src={require('@/assets/images/close-modal.png')} onClick={closeIcon} />}
        >
            <div className="modal-title">Filter</div>
            <Form
                name="filter-form"
                className="filter-form"
                form={filterForm}
                layout="vertical"
                onFinish={onFinish}
                validateTrigger="onBlur"
                autoComplete="off"
            >
                <div>
                    {formItems.map(i => {
                        return (
                            <Form.Item label={i.label} name={i.key} key={i.key}>
                                {i.type === 'select' ? (
                                    <Select
                                        className="form-select"
                                        suffixIcon={
                                            <img
                                                src={require('@/assets/images/arrowDown.png')}
                                                style={{ width: 20, height: 20 }}
                                            />
                                        }
                                        placeholder={i.placeholder}
                                    >
                                        {i.options.map(o => {
                                            return (
                                                <Select.Option value={o.value} key={o.value}>
                                                    {o.label}
                                                </Select.Option>
                                            );
                                        })}
                                    </Select>
                                ) : (
                                    <RangePicker
                                        placeholder={['dd/mm/yyyy', 'dd/mm/yyyy']}
                                        separator="-"
                                        format="DD/MM/YYYY"
                                        suffixIcon={<img src={require('@/assets/images/calendar.png')} alt="" />}
                                        disabledDate={disabledDate}
                                        onChange={dateOnChange}
                                    />
                                    // prevIcon={<img src={require('@/assets/images/prevIcon.png')} alt="" />}
                                    // nextIcon={<img src={require('@/assets/images/nextIcon.png')} alt="" />}
                                )}
                            </Form.Item>
                        );
                    })}

                    <Form.Item label="Place of residence" name="Place of residence">
                        <Cascader
                            className="form-select"
                            options={cascaderOptions}
                            placeholder="Select city"
                            loadData={loadData}
                            onChange={onChange}
                            changeOnSelect
                            suffixIcon={
                                <img src={require('@/assets/images/arrowDown.png')} className="cascaderIcon" alt="" />
                            }
                        />
                    </Form.Item>
                </div>
            </Form>
            <div className="submit-btns">
                <Button onClick={closeModal}>Reset</Button>
                <Button type="primary" onClick={filterOver}>
                    Filter
                </Button>
            </div>
        </Modal>
    );
};
export default FilterModal;
